export default {
  /**
   * Message 消息提示
   * success/warning/info/error
   * @param text
   * @param type
   */
  message(text, type) {
    _bus.$message({
      message: text,
      type: type,
      center: true,
      duration: 1000
    })
  },
  getBase64(img) {
    var image = new Image();
    image.crossOrigin = '';
    image.src = img;
    var deferred = $.Deferred();
    if (img) {
      image.onload = function () {
        deferred.resolve(getBase64Image(image)); //将base64传给done上传处理
      }
      return deferred.promise(); //问题要让onload完成后再return sessionStorage['imgTest']
    }
  },
  getBase64Image(img, width, height) { //width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
    var canvas = document.createElement("canvas");
    canvas.width = width ? width : img.width;
    canvas.height = height ? height : img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var dataURL = canvas.toDataURL();
    return dataURL;
  },

  /*liuhua add --start-2019-4-28-----   */
  /**
   * @name 判断传入地址的图片是否加载成功
   * @param {str} imgurl
   * @param {function} callback
   */
  imgLoad(imgurl, callback) {
    var img = new Image()
    img.src = imgurl
    if (callback) {
      callback()
    }
    return img.complete
  },

  /**
   * @name 倒计时
   * @param {int} time
   * @param {function} callback
   */
  countDown(time, callback) {
    var timeDown = setInterval(() => {
      // return time
      if (time == 0) {
        clearInterval(timeDown)
        if (callback) callback()
      } else {
        time--
      }
    }, 1000)
  },

  /**
   * @name 获取当前路由path
   * @param {*} vue
   */
  getRouterPath(vue) {
    var routerPath = vue.$router.history.current.path
    return routerPath
  },

  /**
   * @name 获取当前路由中携带的参数，返回param或者返回全部的参数
   * @param {*} vue
   * @param {str} param
   */
  getRouterParams(vue, param) {
    if (param) {
      return vue.$router.history.current.params.param
    } else {
      return vue.$router.history.current.params
    }
  },

  getBacImg(vue) {
    return (
      'background:url(' +
      localStorage.getItem('homepageImg') +
      ');background-position-x:' +
      vue.$store.state.homePageBac.positionX +
      ';background-position-y:' +
      vue.$store.state.homePageBac.positionY +
      ';background-size:' +
      vue.$store.state.homePageBac.bacSize
    )
  },

  /**
   * @name 从array中获取符合的obj
   */
  getRightItem(array, key, value) {
    for (var item of array) {
      if (item[key] == value) {
        return item
      }
    }
  },

  /**
   * @name 信息提示窗口
   * @param {*} res
   * @param {function} callback 回调函数
   */
  toMessage(res, callback) {
    if (!res) return
    window._bus.$message({
      type: res.status == 0 ? 'success' : 'error',
      message: res.msg || res.data
    }, {
      duration: 1000,
      center: true
    })
    if (res.status == 0 && callback) {
      callback()
    }
  },

  /**
   * @name 调用方法序列
   * @param {*} array
   */
  async orderMethods(array = []) {
    for (var i = 0; i < array.length; i++) {
      await array[i]()
    }
  },

  /**
   * @name 检查参数
   * @param {*} model 数据模板
   * @param {*} params 检查的数据
   */
  checkParams(model, params) {
    if (!model) throw new Error('数据模板不能为空')
    if (!params) throw new Error('检查的数据不能为空')
    for (var i = 0; i < model.length; i++) {
      if (model[i].checked && !params[model[i].prop]) {
        _g.toMessage({
          status: 1,
          msg: model[i].label + '不能为空'
        })
        return true
      }
    }
    return false
  },

  /**
   * @name apiPost 封装post方法
   * @param {*} url
   * @param {*} data
   */
  async apiPost(url, data, useCheck) {
    // alert('调用post方法')

    var path = PATH + url
    var result = null
    // console.log(path)
    if (useCheck) {
      if (!(await _g.autoTestFormal(data))) {
        return undefined
      }
    }

    try {
      await _axios
        .post(path, qs.stringify(data), {
          withCredentials: true
        })
        .then(res => {
          result = res
          // console.log(res)
          if (res.data.status == 10) {
            _g.toMessage({
              type: 'warning',
              msg: '请重新登录'
            })
            setTimeout(() => {
              location.href = '/login'
            }, 2000)
          }
        })
    } catch (err) {
      var message = '出问题了'
      switch (
        err
        .toString()
        .split('')
        .slice(-1)[0]
      ) {
        case '404':
          message = '访问地址不正确'
          break
        case '500':
          message = '后台出错'
          break
      }
      _g.toMessage({
        type: 'warning',
        msg: message
      })
    }
    return (await result) ? result.data : null
  },
  bankAPI(bankCard) {
    _axios
      .get(
        'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=' +
        bankCard +
        '&cardBinCheck=true'
      )
      .then(res => {
        return res
      })
  },
  /**
   * @name 自动验证输入格式
   */
  autoTestFormal(params = {}) {
    var rules = new Map([
      [
        'phone',
        {
          label: '手机号',
          exp: /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        }
      ],
      ['password', {
        label: '密码',
        exp: /.{6,18}/
      }],
      ['yards', {
        label: '验证码',
        exp: /.{6}/
      }],
      [
        'idno',
        {
          label: '身份证',
          exp: /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
        }
      ]
    ])

    for (var key in params) {
      let ruleinfo = rules.get(key)
      if (ruleinfo && !ruleinfo.exp.test(params[key])) {
        _g.toMessage({
          type: 'warning',
          msg: ruleinfo.label + '格式不正确'
        })
        return false
      }
    }
    return true
  },

  /**
   * @name 生成[num]的数组
   * @param {*} num
   */
  getNumArray(num) {
    return new Array(num).fill('').map((val, index) => index + 1)
  },

  // 全屏
  /**
   * @name 全屏显示局部元素
   * @param {*} id
   * @param {*} vue
   * @param {function} callback
   */
  fullScreen(id, vue, callback) {
    if (!id) throw new Error('全屏元素的id必填')

    let fullarea = document.getElementById(id)

    if (vue.isFullScreen) {
      // 退出全屏
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen()
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      }
    } else {
      // 进入全屏
      if (fullarea.requestFullscreen) {
        fullarea.requestFullscreen()
      } else if (fullarea.webkitRequestFullScreen) {
        fullarea.webkitRequestFullScreen()
      } else if (fullarea.mozRequestFullScreen) {
        fullarea.mozRequestFullScreen()
      } else if (fullarea.msRequestFullscreen) {
        // IE11
        fullarea.msRequestFullscreen()
      }
    }

    if (callback) {
      setTimeout(() => {
        callback()
      }, 200)
    }

    vue.$set(vue, 'isFullScreen', !vue.isFullScreen)
  },

  /**
   * @name 单个数字转换为大写
   * @param {*} word
   */
  toUp(word) {
    switch (word) {
      case '0':
        return '零'
      case '1':
        return '壹'
      case '2':
        return '贰'
      case '3':
        return '叁'
      case '4':
        return '肆'
      case '5':
        return '伍'
      case '6':
        return '陆'
      case '7':
        return '柒'
      case '8':
        return '捌'
      case '9':
        return '玖'
    }
  },

  /**
   * @description 加密
   * @param {str} str
   */
  encrypt(str, type) {
    let array = [
      ['身份证', [6, 14]]
    ]
    let res = new Map(array).get(type)
    return (
      str.slice(0, res[0]) +
      new Array(res[1] - res[0]).fill('*').join('') +
      str.slice(res[1])
    )
  },
  /**
   *
   *
   * @param {*} tel手机号加密
   * @returns
   */
  encryptTel(tel) {
    var reg = /(\d{3})\d{4}(\d{4})/
    return tel.replace(reg, '$1****$2')
  },

  /**
   * @name 找出所有元素
   * @param {string} string
   */
  findAll(array, string) {
    let res = []
    let keyValue = string.split('=')
    let [key, value] = keyValue
    array.forEach(ele => {
      if (ele[key] == value) {
        res.push(ele)
      }
    })
    return res
  },

  /**
   * @name  本机下载
   * @param content
   * @param filename
   */
  formatFile(content, filename) {
    var eleLink = document.createElement('a')
    eleLink.download = filename
    eleLink.style.display = 'none' // 字符内容转变成blob地址
    var blob = new Blob([content])
    eleLink.href = URL.createObjectURL(blob) // 触发点击
    document.body.appendChild(eleLink)
    eleLink.click() // 然后移除
    document.body.removeChild(eleLink)
  },
  /**
   * 替换对象的属性名
   * @param {*} val  被替换的对象 
   * @param {*} nameA /原对象名/g
   * @param {*} nameB  '修改对象名'
   */
  changeName(val, nameA, nameB) {
    let a = JSON.stringify(val).replace(nameA, nameB)
    return JSON.parse(a)
  },
  /**
   * 将换行符替换成标签
   * @param {*} strValue 需要修改的文本
   */
  getTextAreaTo(strValue) {
    return strValue.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ');
  },
  /**
   * 将标签替换成换行符
   * @param {*} strValue 
   */
  getToTextArea(strValue) {
    return strValue.replace(/<br\/>/g, '\n').replace(' ', '\s');
  },
  /**
   *数组去重
   *
   * @returns
   */
  unique5(arr) {
    var x = new Set(arr)
    return [...x]
  },
  // 去掉无用参数
  formatParams(params) {
    if (!params) return undefined
    let ret = {}
    if (Array.isArray(params)) {
      ret = []
    }
    Object.keys(params).forEach(item => {
      if (!!params[item] || params[item] === 0) {
        ret[item] = params[item]
      }
    })
    return ret
  },
  /**
   * encodeToURIString 把一个对象类型转化为问号参数类型的字符串
   * @param data 要解析的对象
   * @param isUIR 是否转化为URIComponent，默认转化，只有当值为false时，不转化
   * @returns '' 问号参数类型的字符串
   */
  encodeToURIString(data, isUIR) {
    //默认参数isUIR不为false，值皆为true
    if (isUIR !== false) {
      isUIR = true;
    }
    var ary = [];
    if (Object.prototype.toString.call(data) === '[object Object]') {
      for (var key in data) {
        if (data.hasOwnProperty(key)) {
          if (isUIR) {
            try {
              key = decodeURIComponent(key);
              data[key] = decodeURIComponent(data[key]);
              ary.push(key + '=' + encodeURIComponent(data[key]));
            } catch (ex) {
              ary.push(key + '=' + data[key]);
            }
          } else {
            ary.push(key + '=' + data[key]);
          }
        }
      }
    }

    return ary.join('&');
  },
  /**
   * paddStringToUrl 将对象转化为问号参数形式添加在url地址的后面，会进行URI编码处理
   * @param url 原url地址
   * @param param 参数对象
   * @returns '' 返回拼接好的新url地址
   */
  paddStringToUrl(url, param) {
    if (!param) {
      return url;
    }
    var hasSearch = /\?/.test(url);
    var data = this.encodeToURIString(this.formatParams(param));
    return url + (hasSearch ? '&' : '?') + data;
  },

  /**
   * @name 拓展方法
   * @param {*} name
   * @param {*} method
   */
  fn(name, method) {
    if (!method) throw new Error('拓展方法未定义')
    if (Object.keys(this).includes(name))
      throw new Error('方法名' + name + '重复')
    this[name] = method
  }
  /*liuhua add --end-2019-4-28-----   */
}